#include <stdio.h>
#include "gnthrdqueue.h"

namespace SMysqlSpace {
	CThrdQueue::CThrdQueue(void) {
		m_pArray	= NULL;
		m_nHead		= 0;
		m_nTail		= 0;
		m_nSize		= 0;
	}

	CThrdQueue::~CThrdQueue(void) {
		if(m_pArray != NULL) {
			delete [] m_pArray;
			m_pArray = NULL;
		}
	}

	bool CThrdQueue::Init(int nSize) {
		m_pArray = new void*[nSize];
		m_nSize = nSize;
		return true;
	}

	bool CThrdQueue::PushBack(void* ptr) {
		int nDist = m_nTail + m_nSize - m_nHead;
		int nUsed = nDist >= m_nSize ? (nDist-m_nSize) : nDist;

		if(nUsed >= m_nSize-1)
			return false;

		m_pArray[m_nTail] = ptr;
		if(++m_nTail >= m_nSize)
			m_nTail = 0;

		return true;
	}

	void* CThrdQueue::PopFront() {
		int nDist = m_nTail + m_nSize - m_nHead;
		int nUsed = nDist >= m_nSize ? (nDist-m_nSize) : nDist;
		if(0 == nUsed)
			return NULL;

		void* ptr = m_pArray[m_nHead];
		if(++m_nHead >= m_nSize)
			m_nHead = 0;

		return ptr;
	}

	bool CThrdQueue::Empty() const {
		int nDist = m_nTail + m_nSize - m_nHead;
		int nUsed = nDist >= m_nSize ? (nDist-m_nSize) : nDist;
		return nUsed == 0;
	}
}
